/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

    //统计个数
    void _sumRootToLeaf(TreeNode* root,vector<int>&select,vector<vector<int>>& result)
    {
        if(root==nullptr)
        {
            return ;
        }

        //入数据
        select.push_back(root->val);

        //遍历
        _sumRootToLeaf(root->left,select,result);
        _sumRootToLeaf(root->right,select,result);
        //入结果集
        if(root->left==root->right)
        {
            result.push_back(select);
        }
        select.pop_back();
    }

    //二进制转十进制
    int change(vector<int>&d1)
    {
        int ret=0;
        int count=0;
        for(int i =d1.size()-1;i>=0;i--)
        {
            if(d1[i]==1)
            ret+=pow(2,count);

            count++;
        }
        return ret;
    }
    int sumRootToLeaf(TreeNode* root)
    {
        //用到了回溯算法

        //特殊处理
        if(root->left==root->right)
        {
            return root->val;
        }

        //待选集
        vector<int> select;
        //结果集
        vector<vector<int>> result;

        _sumRootToLeaf(root,select,result);

        //翻译结果
        int ret=0;
        for(auto ch:result)
        {
            ret+=change(ch);
        }
        return ret;
    }
};
